package com.tojabo.swing.fourteen_table;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableCellRendererDemo1 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public TableCellRendererDemo1() {
		/* 表格列向量 */
		Vector cell;
		/* 表格行向量 */
		Vector row = new Vector();
		/* 声明表格模型 */
		DefaultTableModel tableModel = new DefaultTableModel();
		/* 声明表格头数组 */
		String[] tableHeads = { "ID", "姓名", "年龄", "城市" };
		/* 将表格头转换过向量类型，以备表格模型使用 */
		Vector tableHeadName = new Vector();
		for (int i = 0; i < tableHeads.length; i++) {
			tableHeadName.add(tableHeads[i]);
		}
		/* 初始化表格数据，这些数据实例运行来源于数据库中 */
		for (int i = 1; i <= 100; i++) {
			cell = new Vector();
			cell.add("" + i);
			cell.add(" 水如清" + i);
			cell.add(" 22");
			cell.add(" 深圳");
			row.add(cell);
		}
		/* 设置表格模型 */
		tableModel.setDataVector(row, tableHeadName);
		/* 表格使用模型 */
		JTable table = new JTable(tableModel);
		table.setRowHeight(20);
		/* new Cursor(1)设置鼠标指针样式,12为手形 */
		table.setCursor(new Cursor(12));
		
		  //table.setSelectionBackground(Color.black);
		  //table.setSelectionForeground(Color.white);
		  //table.setGridColor(Color.black); 
		  makeFace(table);
		 // table.setBackground(new Color(206,120,50));
		 // table.setCellSelectionEnabled(false);
		 
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setCursor(new Cursor(12));
		this.getContentPane().add(scrollPane);
		this.setTitle("使用JTable表格的例子");
		this.setSize(400, 300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	/* 表格间隔色显示方法 */
	public static void makeFace(JTable table) {

		try {
			DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
				public Component getTableCellRendererComponent(JTable table,
						Object value, boolean isSelected, boolean hasFocus,
						int row, int column) {
					if (row % 2 == 0)
						setBackground(Color.white); /* 设置奇数行底色 */
					else if (row % 2 == 1)
						setBackground(new Color(206, 231, 255)); /* 设置偶数行底色 */
					return super.getTableCellRendererComponent(table, value,
							isSelected, hasFocus, row, column);
				}
			};
			for (int i = 0; i < table.getColumnCount(); i++) {
				table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TableCellRendererDemo1 table = new TableCellRendererDemo1();
	}

}
